#!/usr/bin/env bash
set -euo pipefail

# This script bumps the Sentry JavaScript SDK used by the Flutter web integration.
# The expected interface is identical to the other updater scripts used by the
# monorepo so that it can be consumed by the generic getsentry/updater workflow.
#
# Usage: ./update-js.sh <command>
#   get-version   – prints the currently used SDK version (read from sentry-js-sdk.yaml)
#   get-repo      – prints the upstream Git repository URL
#   set-version X – updates the version to X, refreshes integrity hashes and
#                   regenerates the Dart constant file used by the web runtime

VERSION_DART_FILE="$(git rev-parse --show-toplevel)/packages/flutter/lib/src/web/sentry_js_sdk_version.dart"

get_current_version() {
  awk -F"'" '/sentryJsSdkVersion/ { print $2 }' "$VERSION_DART_FILE"
}

# Regenerates the Dart helper that exposes the SDK version as a compile-time
# constant so that the rest of the code can simply import it.
write_version_dart() {
  local version="$1"
  local integrity_prod="$2"
  local integrity_dbg="$3"
  cat >"$VERSION_DART_FILE" <<EOF
import 'package:meta/meta.dart';

/// DO NOT EDIT – generated by scripts/update-js.sh
@internal
const sentryJsSdkVersion = '$version';

@internal
const productionIntegrity =
    'sha384-$integrity_prod';

@internal
const debugIntegrity =
    'sha384-$integrity_dbg';
EOF
}

case "${1:-}" in
  get-version)
    get_current_version
    ;;

  get-repo)
    echo "https://github.com/getsentry/sentry-javascript.git"
    ;;

  set-version)
    new_version="$2"

    # Fetch SRI hashes for the given version.
    min_js_url="https://browser.sentry-cdn.com/$new_version/bundle.tracing.min.js"
    dbg_js_url="https://browser.sentry-cdn.com/$new_version/bundle.tracing.js"

    # Compute the SHA-384 SRI hashes (without the sha384- prefix)
    integrity_prod=$(curl -sSL "$min_js_url" | openssl dgst -sha384 -binary | openssl base64 -A)
    integrity_dbg=$(curl -sSL "$dbg_js_url" | openssl dgst -sha384 -binary | openssl base64 -A)

    # Persist changes
    write_version_dart "$new_version" "$integrity_prod" "$integrity_dbg"
    ;;

  *)
    echo "Unknown argument $1" >&2
    exit 1
    ;;
esac
